const { request, smms } = require('../axios/axios-main')
const env = 'my-book-assist-7gc4zqa8552557ed'

// 获取所有可借阅书籍（新建角色）
exports.getAllAvaiBooks = (_data) => {
  const data = {
    env,
    query: `db.collection('books').where({status: true}).limit(999).skip(1).get()`
  }
  return request({
    method: 'POST',
    url: `/tcb/databasequery?access_token=${_data.access_token}`,
    data
  })
}

// 获取所有书籍（书籍首页和书籍查询空条件）
exports.getAllBooks = (_data) => {
  const limit = _data.pageSize ? parseInt(_data.pageSize) : 1000
  const skip = _data.curPage ? (parseInt(_data.curPage) - 1) * limit : 0
  const data = {
    env,
    query: `db.collection('books').limit(${limit}).skip(${skip}).get()`
  }
  return request({
    method: 'POST',
    url: `/tcb/databasequery?access_token=${_data.access_token}`,
    data
  })
}

// 获取集合信息，以获取书籍数据库总大小
exports.getBooksSize = (_data) => {
  const data = {
    env,
    limit: 10,
    offset: 0
  }
  return request({
    method: 'POST',
    url: `/tcb/databasecollectionget?access_token=${_data.access_token}`,
    data
  })
}

// 获取书籍查询下拉菜单
exports.getTypeList = (_data) => {
  const data = {
    env,
    query: `db.collection('types').limit(50).skip(0).get()`
  }
  return request({
    method: 'POST',
    url: `/tcb/databasequery?access_token=${_data.access_token}`,
    data
  })
}

// 查询书籍
exports.queryBooks = (_data) => {
  let where = ''
  const limit = _data.pageSize !== -1 ? parseInt(_data.pageSize) : 1000
  const skip = _data.pageSize !== -1 ? (parseInt(_data.curPage) -1) * limit : 0
  let paramsCount = -3
  for (let key in _data) {
    if (_data[key]) {
      paramsCount++
    }
  }
  // 只有一个查询参数
  if (paramsCount === 1) {
    if (_data.bookName) {
      where += `db.collection('books').where({
        bookName: db.RegExp({
          regexp: '.*${_data.bookName}',
          option: 'i'
        })
      })`
    } else if (_data.bookId) {
      where += `db.collection('books').where({
        bookId: ${_data.bookId} 
      })`
    } else if (_data.type) {
      where += `db.collection('books').where({
        type: ${_data.type} 
      })`
    }
  } else if (paramsCount === 2) {  // 两个查找参数
    if (!_data.bookName) {
      where += `db.collection('books').where(db.command.and([
        {
          type: ${_data.type}
        },
        {
          bookId: ${_data.bookId} 
        }
      ]))`
    } else if (!_data.type) {
      where += `db.collection('books').where(db.command.and([
        {
          bookName: db.RegExp({
            regexp: '.*${_data.bookName}',
            option: 'i'
          })
        },
        {
          bookId: ${_data.bookId} 
        }
      ]))`
    } else {
      where += `db.collection('books').where(db.command.and([
        {
          type: ${_data.type}
        },
        {
          bookName: db.RegExp({
            regexp: '.*${_data.bookName}',
            option: 'i'
          })
        }
      ]))`
    }
  } else if (paramsCount === 3) {  // 三个查找参数
    where += `db.collection('books').where(db.command.and([
      {
        type: ${_data.type}
      },
      {
        bookName: db.RegExp({
          regexp: '.*${_data.bookName}',
          option: 'i'
        })
      },
      {
        bookId: ${_data.bookId} 
      }
    ]))`
  } else {  // 出了意外
    return false
  }
  const data = {
    env,
    query: `${where}.limit(${limit}).skip(${skip}).get()`
  }
  return request({
    method: 'POST',
    url: `/tcb/databasequery?access_token=${_data.access_token}`,
    data
  })
}

// 获取最后一本书
exports.getLastBookId = (_data) => {
  const data = {
    env,
    query: `db.collection('books').skip(${_data.length - 1}).get()`
  }
  return request({
    method: 'POST',
    url: `/tcb/databasequery?access_token=${_data.access_token}`,
    data
  })
}

// 添加书本
exports.addBook = async (_data) => {
  // 1. 先获取最后那条数据的 _id 将其 _id + 1 赋值给添加的数据
  // 2. 首先获取数据库总大小 getBooksSize
  // 3. 根据 skip 数获取最后一条 skip - 1 ，getLastBookId
  // 4. 赋值后提交
  const lengthObj = await this.getBooksSize(_data)
  let length = null
  for (let i = 0; i < lengthObj.data.collections.length; i++) {
    if (lengthObj.data.collections[i].name === 'books') {
      length = lengthObj.data.collections[i].count
      break
    }
  }
  const dataForLastBook = {
    access_token: _data.access_token,
    length
  }
  const lastBook = await this.getLastBookId(dataForLastBook)
  const lastBookData = JSON.parse(lastBook.data.data[0])
  const dataJSON = JSON.parse(JSON.stringify(_data))
  delete dataJSON.access_token
  dataJSON._id = parseInt(lastBookData._id) + 1
  dataJSON.bookId = parseInt(lastBookData._id) + 1
  const data = {
    env,
    query: `db.collection('books').add({
      data: [${JSON.stringify(dataJSON)}]
    })`
  }
  return request({
    method: 'POST',
    url: `/tcb/databaseadd?access_token=${_data.access_token}`,
    data
  })
}

// 上传图片
exports.uploadImage = (_data) => {
  const file = _data.file
  const data = {
    file
  }
  return request({
    method: 'POST',
    url: `/tcb/invokecloudfunction?access_token=${_data.access_token}&env=${env}&name=uploadImage`,
    data
  })
}

// 获取下载地址
exports.getImageURL = (_data) => {
  const data = {
    env,
    file_list: [{
      fileid: _data.fileid,
      max_age: 7777
    }]
  }
  return request({
    method: 'POST',
    url: `/tcb/batchdownloadfile?access_token=${_data.access_token}`,
    data
  })
}

// 根据bookId获取书本
exports.getBook = (_data) => {
  const where = `{
    bookId: ${parseInt(_data.bookId)}
  }`
  const data = {
    env,
    query: `db.collection('books').where(${where}).limit(1).get()`
  }
  return request({
    method: 'POST',
    url: `/tcb/databasequery?access_token=${_data.access_token}`,
    data
  })
}

// 强制归还书本
exports.giveBackBook = (data) => {
  return request({
    method: 'POST',
    url: `/tcb/invokecloudfunction?access_token=${data.access_token}&env=${env}&name=giveBackBook`,
    data
  })
}

// 编辑书籍提交
exports.editBook = (data) => {
  return request({
    method: 'POST',
    url: `/tcb/invokecloudfunction?access_token=${data.access_token}&env=${env}&name=editBook`,
    data
  })
}
